<script setup lang="jsx">
  import {watch,inject,ref,nextTick,reactive,computed} from 'vue'
import waybillTaskSend from '@/api/abroad/waybillTaskSend'
import { Message, Modal } from '@arco-design/web-vue'
import shipment from "@/views/abroad/waybillTaskSend/components/shipment.vue";
import dicthelpApi from "@/api/dicthelpApi.js";
import {getDictData} from "@/utils/crud/dictNew.js";
const columnsDist = inject('columnsDist')
const span=ref(6)
const formRef=ref(null)
// const trayRef=ref()
const shipmentRef=ref()
// 表单数据
const rules = {
      type: [{ required: true, message:'请选择服务类型',validateTrigger: 'blur'}, ],
      address: [{ required: true, message:'请选择目的地',validateTrigger: 'blur'}, ],
      title: [{ required: true, message:'请输入标题',validateTrigger: 'blur'}, ],
  }
const shipmentList=ref([])
const addressList=ref([])
const formData = ref({
  id:'',
  type:'',
  address:'',
  title: "", 
  remark: "", 
  tracking_no:'',
  car_id: null, 
  eta:null,
  close_at:null,
  shipment:[],
  status:null,
})
const visible = ref(false)
 const addTrayList = (type) => {
  shipmentRef.value.open()  
}
  
//删除tabel
const deleteAction=(index,type)=>{
  shipmentList.value.splice(index,1)  
}
//类型切换
   const typeChang=(e,type)=>{
      dicthelpApi.addressChang(e).then(res => {
        if(!type){
         formData.value.address=''
        }
        addressList.value=res.data
    })    
    }
const columnsShipment = ref([  
  {title: '箱唛', dataIndex: 'shipment.shipment_no',width:70,hide:true,},
  {title: '目的地', dataIndex: 'address_desc',slotName: 'address_desc',width:100,align:'center',hide:true,},
  {title: '柜号', dataIndex: 'shipment.container_no',width:70,hide:true,},
  {title: '箱数', dataIndex: 'count',width:70,hide:true,},
  {title: '托盘组编号', dataIndex: 'tray.number',width:150,hide:true,align:'center',},
  {title: '托盘编号', dataIndex: 'tray_list',slotName: 'tray_list',width:150,hide:true,align:'center',},
  {title: '操作', slotName: 'fixed',fixed: 'right',width: 70,align:'center'},

]);
//合计
const summary = ({columns, data}) => {
    if(data.length>0){
      let countData = {
          count:0,
        };
        data.forEach(record => {
          countData.count += record.count;
        })

        return [{
          count:'合计：'+countData.count.toFixed(2),
        }]
    }  
  }
//选择的托盘并去重
const tableListPrant=(data,type)=>{
  let trays=shipmentList.value
    let newTrays=trays.concat(data)
    let list=[]
    let uninewTrays=newTrays.filter((item) => !list.includes(item.shipment_id) && list.push(item.shipment_id))
    shipmentList.value=uninewTrays
}
 //详情
 const infoGet=(id)=>{
  waybillTaskSend.read(id).then(res => {
        formData.value=res.data
        shipmentList.value=res.data.shipment
        typeChang(res.data.type,'init')
      })
     
    }
  const onShow = async (value) => {
    visible.value = true
    //编辑
    if(value){
      infoGet(value.id) 
    }
  }



const emits = defineEmits(['addClick','emitClick'])
  //新增 //编辑
  const handleBeforeOk =async (formEl) => {
    // return false
      let formParse = JSON.parse(JSON.stringify(formData.value)); // 深拷贝数据
      console.log('formParse',formParse)
      formParse.shipment=[]
      shipmentList.value.map((item,index)=>{
        formParse.shipment.push(item.shipment_id)
      })
    if (!formEl) return
      await formEl.validate((valid) => {
        if (!valid) {
          if(formParse.id==''){
            waybillTaskSend.save(formParse).then(res => {
              Message.success(res.message || `新增成功！`)
              emits('addClick');
              close()
            })
          }else{
            waybillTaskSend.update(formParse).then(res => {
              Message.success(res.message || `编辑成功！`)
              emits('addClick');
              close()
            })
          }
          
        }
      }) 
      
    };

    const close = () => {
      formRef.value.resetFields();
      visible.value = false
      formData.value.id=''
      formData.value.car_id=null
      formData.value.close_at=null
      formData.value.status=null
      formData.value.shipment=[]
      shipmentList.value=[]
    }
const onBeforeCancel=()=>{
  Modal.confirm({
        title: '确认关闭?',
        onOk: () => {
          close()
        },
      });
}
defineExpose({ onShow })
</script>

<template>
  <a-drawer v-model:visible="visible" v-if="visible" width="80%" :onBeforeCancel="onBeforeCancel">
        <template #title>
          <div >{{  formData.id == "" ? '新增' : '编辑'}}</div>
          </template>
          <a-form ref="formRef" :rules="rules" :model="formData" auto-label-width >
            <div class="form-top-main">
              
            <a-col :span="span">
              <a-form-item field="title" label="标题" validate-trigger="change">
                <a-input v-model="formData.title"  placeholder="请输入标题" />
              </a-form-item>
            </a-col>
            <a-col :span="span">
              <a-form-item field="type" label="服务类型" validate-trigger="change">
                <a-select v-model="formData.type" @change="typeChang"  :options="columnsDist.dicthelpApi_waybillServiceShipmentTypeList.data" :field-names="{ value: 'id', label: 'name' }"
                placeholder="请选择服务类型" allow-clear allow-search :virtual-list-props="{height:200}" /> 
              </a-form-item>
            </a-col>
            <a-col :span="span">
              <a-form-item field="address" label="目的地" validate-trigger="change">
                <a-select v-model="formData.address" :disabled="formData.type==''" :options="addressList"
                placeholder="请选择目的地" allow-clear allow-search :virtual-list-props="{height:200}" /> 
              </a-form-item>
            </a-col>
            <a-col :span="span" v-if="formData.id==''">
              <a-form-item label="车辆" validate-trigger="change" field="car_id">
                <a-select v-model="formData.car_id"
                placeholder="请选择车辆" allow-clear allow-search>
                <a-option v-for="item in columnsDist.dicthelpApi_waybillCarList.data" :value="item.id" :key="item.id">{{item.car_number}}</a-option>     
              </a-select> 
              </a-form-item>
            </a-col>
            <a-col :span="span">
              <a-form-item field="tracking_no" label="追踪编号" validate-trigger="change">
                <a-input v-model="formData.tracking_no"  placeholder="请输入追踪编号" />
              </a-form-item>
            </a-col>
            <a-col :span="span">
              <a-form-item field="eta" label="预计送达时间" validate-trigger="change">
                <a-date-picker
                  style="width: 100%;"
                  placeholder="预计送达时间"
                  v-model="formData.eta"
                />
              </a-form-item>
            </a-col>
            <a-col :span="span">
              <a-form-item field="close_at" label="送达时间" validate-trigger="change">
                <a-date-picker
                  style="width: 100%;"
                  placeholder="送达时间"
                  :disabled="formData.status<4"
                  v-model="formData.close_at"
                />
              </a-form-item>
            </a-col>

            <a-col :span="24">
              <a-form-item field="remark" label="描述" validate-trigger="change">
                <a-textarea v-model="formData.remark"  placeholder="请输入描述" />
              </a-form-item>
            </a-col>         
          </div>
          <div style="display: flex;justify-content: space-between;align-items: center;margin: 10px 0;">
            <a-button type="primary" @click="addTrayList(3)">               
          选择运单
        </a-button>
        </div>
        <a-table ref="shipmentTableRef"  row-key="shipment_id" :columns="columnsShipment"  :summary="summary" :data="shipmentList" :bordered="false"  column-resizable :pagination="false">
            <template #service_type_id="{ record }">{{getDictData('attrApi','dicthelpApi_waybillServiceShipmentTypeList',record.tray.service_type_id,3,columnsDist) }}</template>
            <template #address_desc="{ record }">{{record?.address_desc}}</template>
            <template #tray_list="{ record }">
              <div v-for="item in record.tray_list" :key="item.number">{{item.number }}</div>
            </template>
            <template #fixed="{ record,rowIndex }">
              <a-link title="删除" @click="deleteAction(rowIndex,3)"><icon-delete /></a-link>                      
            </template>
            <template #summary-cell="{ column,record,rowIndex }">
                <div style="color:red">{{record[column.dataIndex]}}</div>
              </template>
        </a-table>
        </a-form>
        <template #footer> 
          <div style="display: flex; justify-content: space-between;align-items: center;">
            <div style="color: rgb(50 193 148);">
              <!-- tips：先选择"服务项目"后在操作明细,请按要求填写(导入)单据信息 -->
            </div>
            <div>
              <a-button @click="visible = false" style="margin-right: 20px;">关闭</a-button>
              <a-button type="primary" @click="handleBeforeOk(formRef)">
                保存
              </a-button>
            </div>
          </div>       
        </template>
      </a-drawer>
    <shipment ref="shipmentRef" @addClick="tableListPrant" v-if="visible"></shipment>
</template>
<style>
   .form-top-main{
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    width: 100%;
   }
   .tab-main{
    display: flex;
    align-items: center;
    margin: 10px 0;
   }
   .tab-main .arco-form-item{
    margin-bottom: 0;
   }
   .tab-main .arco-switch{
    margin-right: 20px;
   }
</style>